﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml.Linq;
using CircumferenceRotatePanelControl;
using SensingPlatform.Foundation.Events;
using Path = System.IO.Path;

namespace CircumferenceRotatePanel.Views
{
    /// <summary>
    /// Circumferencel.xaml 的交互逻辑
    /// </summary>
    public partial class Circumferencel : UserControl
    {
        // 旋转控制变量
        private double rotationAngle = 0;
        private double startAngle = 0;
        private Point startPoint;
        private bool isDragging = false;
        private const double RotationSpeedFactor = 0.5; // 旋转灵敏度

        // 图片相对路径
        private const string BackgroundImagePath = "icon/yuanpng.png";
        private const string Button1ImagePath = "icon/shiti.png";
        private const string Button2ImagePath = "icon/shehui.png";
        private const string Button3ImagePath = "icon/wenhua.png";
        private const string Button4ImagePath = "icon/zhuyao.png"; // 重复使用同一图片

        DispatcherTimer dispatcherTimer = new DispatcherTimer();
        Timer timer = new Timer();

        public Circumferencel()
        {
            InitializeComponent();
            InitImg();
        }

        string baseDir = AppDomain.CurrentDomain.BaseDirectory;

        private void InitImg()
        {
            try
            {
                // 获取程序基目录
                string baseDir = AppDomain.CurrentDomain.BaseDirectory;

                // 加载背景图片
                string backgroundFullPath = Path.Combine(baseDir, BackgroundImagePath);
                if (File.Exists(backgroundFullPath))
                {
                    backgroundImage.Source = LoadBitmapImage(backgroundFullPath);
                }
                else { }

                // 加载按钮图片
                btn1Image.Source = LoadBitmapImage(Path.Combine(baseDir, Button1ImagePath));
                btn2Image.Source = LoadBitmapImage(Path.Combine(baseDir, Button2ImagePath));
                btn3Image.Source = LoadBitmapImage(Path.Combine(baseDir, Button3ImagePath));
                btn4Image.Source = LoadBitmapImage(Path.Combine(baseDir, Button4ImagePath));
            }
            catch (Exception ex) { }

            //dispatcherTimer.Interval = TimeSpan.FromMilliseconds(20);
            //dispatcherTimer.Tick += DispatcherTimer_Tick;
            //dispatcherTimer.Start();

            //timer.Elapsed += Timer_Elapsed;
            //timer.AutoReset = false;
            //timer.Interval = 10000;
        }

        private BitmapImage LoadBitmapImage(string filePath)
        {
            if (!File.Exists(filePath))
                return null;

            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad; // 立即加载
            bitmap.UriSource = new Uri(filePath);
            bitmap.EndInit();
            bitmap.Freeze(); // 提高性能（如果不需要修改）
            return bitmap;
        }

        private float speed = 0.04f;
        public List<CircumferenceItem> circumferenceItems = [];

        public void Initialize(XElement config)
        {
            if (config != null)
            {
                int.TryParse(config.Attribute("Width").Value, out int Image_Width);
                int.TryParse(config.Attribute("Height").Value, out int Image_Height);
                int.TryParse(config.Attribute("Radius").Value, out int radius);
                int.TryParse(config.Attribute("Interval").Value, out int interval);
                int.TryParse(config.Attribute("CircleRadius").Value, out int circleRadius);
                int.TryParse(config.Attribute("StopTime").Value, out int stopTime);
                float.TryParse(config.Attribute("Speed").Value, out speed);

                rotationContainer.Width = Image_Width;
                backgroundImage.Width = Image_Width;
                rotationContainer.Height = Image_Height;
                backgroundImage.Height = Image_Height;
                this.Width = Image_Width;
                Height = Image_Height;

                var element = config.Element("Models");
                if (element != null)
                {
                    var ele = element.Elements("Model");
                    foreach (var item in ele)
                    {
                        var img = item.Attribute("Image").Value;
                        int.TryParse(item.Attribute("Width").Value, out int item_w);
                        int.TryParse(item.Attribute("Height").Value, out int item_h);
                        int.TryParse(item.Attribute("Top").Value, out int item_top);
                        int.TryParse(item.Attribute("Left").Value, out int item_left);

                        if (img.Contains("shiti"))
                        {
                            btn1Image.Source = LoadBitmapImage(Path.Combine(baseDir, img));
                            btn1.Height = item_h;
                            btn1.Width = item_w;
                            Canvas.SetTop(btn1, item_top);
                            Canvas.SetLeft(btn1, item_left);
                        }
                        else if (img.Contains("shehui"))
                        {
                            btn2Image.Source = LoadBitmapImage(Path.Combine(baseDir, img));
                            btn2.Height = item_h;
                            btn2.Width = item_w;
                            Canvas.SetTop(btn2, item_top);
                            Canvas.SetLeft(btn2, item_left);
                        }
                        else if (img.Contains("wenhua"))
                        {
                            btn3Image.Source = LoadBitmapImage(Path.Combine(baseDir, img));
                            btn3.Height = item_h;
                            btn3.Width = item_w;
                            Canvas.SetTop(btn3, item_top);
                            Canvas.SetLeft(btn3, item_left);
                        }
                        else if (img.Contains("zhuyao"))
                        {
                            btn4Image.Source = LoadBitmapImage(Path.Combine(baseDir, img));
                            btn4.Height = item_h;
                            btn4.Width = item_w;
                            Canvas.SetTop(btn4, item_top);
                            Canvas.SetLeft(btn4, item_left);
                        }
                        circumferenceItems.Add(
                            new CircumferenceItem
                            {
                                Angle = 100,
                                Width = item_w,
                                Height = item_h,
                                ImagePath = img,
                                Name = img,
                                ClickEvent = item.Value,
                            }
                        );
                    }
                }

                dispatcherTimer.Interval = TimeSpan.FromMilliseconds(interval);
                dispatcherTimer.Tick += DispatcherTimer_Tick;
                dispatcherTimer.Start();

                timer.Elapsed += Timer_Elapsed;
                timer.AutoReset = false;
                timer.Interval = stopTime;
            }
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            StartAuto();
        }

        private void StartAuto()
        {
            StopWatch();
            dispatcherTimer.Start();
        }

        private void StopAuto()
        {
            dispatcherTimer.Stop();
            StartWatch();
        }

        private void Reset()
        {
            StopWatch();
            StartWatch();
        }

        private void StartWatch()
        {
            timer.Start();
        }

        private void StopWatch()
        {
            timer.Stop();
        }

        private void DispatcherTimer_Tick(object sender, EventArgs e)
        {
            startAngle += (1 * speed);
            rotationAngle = startAngle;
            StartSmoothIncrementalRotation();
        }

        public void StartPage(string query)
        {
            if (!string.IsNullOrEmpty(query))
            {
                //Output.Text += query + Environment.NewLine;
                //SensingPlatformEventHelper.TriggerEvent("", this);
            }
        }

        public void StopPage(string query)
        {
            if (!string.IsNullOrEmpty(query))
            {
                //Output.Text += query + Environment.NewLine;
            }
        }

        int a = 1;

        // 统一输入按下处理
        private void Input_Down(object sender, InputEventArgs e)
        {
            DependencyObject target = e.OriginalSource as DependencyObject;
            if (target != null && FindParent<Button>(target) != null)
            {
                // 点击的是按钮或按钮内部，不进行旋转操作，让按钮处理 Click 事件
                a = 1;
                return;
            }
            // 获取初始位置
            if (e is TouchEventArgs touchEvent)
            {
                startPoint = touchEvent.GetTouchPoint(rotationContainer).Position;
            }
            else if (e is MouseButtonEventArgs mouseEvent)
            {
                startPoint = mouseEvent.GetPosition(rotationContainer);
            }

            // 记录初始状态
            isDragging = true;
            startAngle = rotationAngle;

            // 捕获输入
            rotationContainer.CaptureMouse();

            // 标记事件已处理
            e.Handled = true;

            StopAuto();
        }

        // 统一输入移动处理
        private void Input_Move(object sender, InputEventArgs e)
        {
            if (!isDragging)
                return;

            // 获取当前位置
            Point currentPoint;
            if (e is TouchEventArgs touchEvent)
            {
                currentPoint = touchEvent.GetTouchPoint(rotationContainer).Position;
            }
            else if (e is MouseEventArgs mouseEvent)
            {
                currentPoint = mouseEvent.GetPosition(rotationContainer);
            }
            else
            {
                return;
            }

            // 计算相对于旋转中心的向量
            Point center = new Point(
                rotationContainer.ActualWidth / 2,
                rotationContainer.ActualHeight / 2
            );
            Vector startVector = new Vector(startPoint.X - center.X, startPoint.Y - center.Y);
            Vector currentVector = new Vector(currentPoint.X - center.X, currentPoint.Y - center.Y);

            // 计算角度差
            double angle = Vector.AngleBetween(startVector, currentVector);

            // 应用旋转角度
            rotationAngle = startAngle + angle * RotationSpeedFactor;
            ApplyRotation();

            e.Handled = true;
            Reset();
        }

        // 统一输入释放处理
        private void Input_Up(object sender, InputEventArgs e)
        {
            DependencyObject target = e.OriginalSource as DependencyObject;
            if (target != null && FindParent<Button>(target) != null)
            {
                // 点击的是按钮或按钮内部，不进行旋转操作，让按钮处理 Click 事件
                a = 2;
                return;
            }
            if (!isDragging)
                return;

            // 结束拖动
            isDragging = false;
            rotationContainer.ReleaseMouseCapture();

            e.Handled = true;
        }

        private T FindParent<T>(DependencyObject child)
            where T : DependencyObject
        {
            var parent = VisualTreeHelper.GetParent(child);
            while (parent != null && !(parent is T))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            return parent as T;
        }

        // 应用旋转
        private async void ApplyRotation()
        {
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                //创建动画

                //应用整个Canvas的旋转
                //canvasRotate.Angle = rotationAngle;

                //// 应用按钮的反向旋转（保持按钮正立）
                //btn1Rotate.Angle = -rotationAngle;
                //btn2Rotate.Angle = -rotationAngle;
                //btn3Rotate.Angle = -rotationAngle;
                //btn4Rotate.Angle = -rotationAngle;


                //RotateTransform rotateTransform = canvasRotate; // 替换为你的 Canvas 的 RotateTransform
                //double currentAngle = rotateTransform.Angle;
                //double targetAngle = currentAngle + speed; // 每次增加 1 度

                AnimateOneDegree2(canvasRotate, rotationAngle);

                AnimateOneDegree2(btn1Rotate, -rotationAngle);
                AnimateOneDegree2(btn2Rotate, -rotationAngle);
                AnimateOneDegree2(btn3Rotate, -rotationAngle);
                AnimateOneDegree2(btn4Rotate, -rotationAngle);
            });
        }

        private void StartSmoothIncrementalRotation()
        {
            //RotateTransform rotateTransform = canvasRotate; // 替换为你的 Canvas 的 RotateTransform
            //double currentAngle = rotateTransform.Angle;

            rotationAngle = (rotationAngle + speed) % 360; // 每次增加 1 度
            AnimateOneDegree(canvasRotate, rotationAngle);

            AnimateOneDegree(btn1Rotate, -rotationAngle);
            AnimateOneDegree(btn2Rotate, -rotationAngle);
            AnimateOneDegree(btn3Rotate, -rotationAngle);
            AnimateOneDegree(btn4Rotate, -rotationAngle);

        }

        private void AnimateOneDegree(RotateTransform rotateTransform, double targetAngle)
        {
            //double currentAngle = rotateTransform.Angle;
            //double targetAngle = currentAngle + speed; // 每次增加 1 度

            DoubleAnimation animation = new DoubleAnimation
            {
                To = targetAngle,
                Duration = TimeSpan.FromMilliseconds(20), 
                //EasingFunction = new LinearEase() // 线性匀速
            };
            rotateTransform.BeginAnimation(RotateTransform.AngleProperty, animation);
        }

        private void AnimateOneDegree2(RotateTransform rotateTransform, double targetAngle)
        {
            //double currentAngle = rotateTransform.Angle;
            //double targetAngle = currentAngle + speed; // 每次增加 1 度

            DoubleAnimation animation = new DoubleAnimation
            {
                To = targetAngle,
                Duration = TimeSpan.FromMilliseconds(100),
                //EasingFunction = new LinearEase() // 线性匀速
            };
            rotateTransform.BeginAnimation(RotateTransform.AngleProperty, animation);
        }

        private void AnimateOneDegreeReverse(RotateTransform btnTransform, double targetAngle)
        {
            //double currentAngle = btnTransform.Angle;
            //double targetAngle = currentAngle - speed; // 每次增加 1 度

            DoubleAnimation animation = new DoubleAnimation
            {
                To = targetAngle,
                Duration = TimeSpan.FromMilliseconds(20), 
                //EasingFunction = new LinearEase() // 线性匀速
            };
            btnTransform.BeginAnimation(RotateTransform.AngleProperty, animation);
        }

        private void btn1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SensingPlatformEventHelper.TriggerEvent(circumferenceItems[0].ClickEvent, this);
            }
            catch (Exception) { }
        }

        private void btn2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SensingPlatformEventHelper.TriggerEvent(circumferenceItems[1].ClickEvent, this);
            }
            catch (Exception) { }
        }

        private void btn3_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SensingPlatformEventHelper.TriggerEvent(circumferenceItems[2].ClickEvent, this);
            }
            catch (Exception) { }
        }

        private void btn4_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SensingPlatformEventHelper.TriggerEvent(circumferenceItems[3].ClickEvent, this);
            }
            catch { }
        }

        private void btn1_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Debug.WriteLine("点击了");
        }
    }
}
